'use strict';

const Controller = require('egg').Controller;

class ArticleController extends Controller {
  async add() {
    const {ctx,service} = this;
    const json = ctx.request.body;
    json.openid = '666666';
    json.shoptoplvid = ctx.session.admin._id;
    json.author = ctx.session.admin.nickName;
    json.avatarUrl = ctx.session.admin.avatarUrl;
    let result = await service.normal.addinfo('Article',json);
    ctx.body = result;
  }
  async gets() {
    const {ctx,service} = this;
    const {isMe,deleted,author,tab,page,size} = ctx.request.body;
    let json = {author: { $regex: author },isMe,deleted,tab};
    let result = await service.normal.getinfos('Article',json,page,size);
    ctx.body = result;
  }

  async getbytitle() {
    const {ctx,service} = this;
    const {isMe,deleted,title,tab,page,size} = ctx.request.body;
    let json = {title: { $regex: title },isMe,deleted,tab};
    let result = await service.normal.getinfos('Article',json,page,size);
    ctx.body = result;
  }
  async chatgets() {
    const {ctx,service} = this;
    const { openid,shoptoplvid,isMe,deleted,author,tab,page,size } = ctx.request.body;
    let json = {author: { $regex: author },isMe,deleted: false, tab: { $regex: tab },shoptoplvid: shoptoplvid};
    let result = await service.normal.getinfos('Article',json,page,size);
    for(let i=0;i<result.result.result.length;i++){
      let temp = result.result.result[i]
      let reply = await ctx.model.Reply.findOne({articleid: temp._id, openid: openid, atype: 1});
      let isZan = false;
      if(reply){
        isZan = true;
      }
      result.result.result[i].isZan = isZan;
    }
    ctx.body = result;
  }

  
  async getspicle(){
    const {ctx,service} = this;
    const {state,limit} = ctx.request.body;
    let result = await service.normal.getlimits('Article',state,limit);
    ctx.body = result;
  }
  async getone() {
    const {ctx,service} = this;
    const {id} = ctx.request.body;
    let result = await service.normal.getinfobyid('Article',id);
    if(result.data==1){
      let visit_count = result.result.visit_count;
      visit_count++
      await service.normal.statebyid('Article',id,{visit_count});
    }
    ctx.body = result;
  }
  async updateone(){
    const {ctx,service} = this;
    const {id,form} = ctx.request.body;
    let result = await service.normal.updateinfobyid('Article',id,form);
    ctx.body = result;
  }
  async statedone() {
    const {ctx,service} = this;
    const {id,states} = ctx.request.body;
    let result = await service.normal.statebyid('Article',id,states);
    ctx.body = result;
  }
}

module.exports = ArticleController;